package com.ttmusic.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class OnlineLrcUtil implements ILrcStateContain{
	private static String TAG = "OnlineLrcUtil";
	private static OnlineLrcUtil instance;
	//歌词文件保存的根路径
    public static final String lrcRootPath = Environment.getExternalStorageDirectory().toString()
            + "/Music/Musiclrc/";

	public static final String queryLrcURLRoot = "http://geci.me/api/lyric/";

	public static OnlineLrcUtil getInstance() {
		if (null == instance) {
			instance = new OnlineLrcUtil();
		}
		return instance;
	}

	/**
	 * 歌曲名称和艺术家名称中文时一定要转码成UTF-8
	 * @param title
	 * @param artist
	 * @return
	 */
	private String getQueryLrcURL(String title, String artist) {
		String queryLrcURL = queryLrcURLRoot + Encode(title) + "/" + Encode(artist);
		if(queryLrcURL.contains("+"))
			queryLrcURL = queryLrcURL.replace("+", " ");
		return queryLrcURL;
	}
	
	/**
	 * 歌曲名称和艺术家名称中文时一定要转码成UTF-8   ------  只要歌曲名称
	 * @param title
	 * @param artist
	 * @return
	 */
	private String getQueryLrcURLOnlyTitle(String title) {
		String queryLrcURL = queryLrcURLRoot + Encode(title);
		if(queryLrcURL.contains("+"))
			queryLrcURL = queryLrcURL.replace("+", " ");
		return queryLrcURL;
	}

	/**
	 * 比如我要查询：   http://geci.me/api/lyric/安静/周杰伦
	 * 会得到一下json串：
	 * {"count": 2, "code": 0, 
	 * 		"result": [
	 * 			{"aid": 2223011, "artist_id": 30796, "song": "\u5b89\u9759", "lrc": "http://s.geci.me/lrc/257/25700/2570058.lrc", "sid": 2570058}, 
	 * 			{"aid": 2336033, "artist_id": 30796, "song": "\u5b89\u9759", "lrc": "http://s.geci.me/lrc/272/27282/2728244.lrc", "sid": 2728244}
	 * 		]
	 * }
	 * @param title
	 * @param artist
	 * @param handler 跨线程消息传输工具
	 */
	public void getLrcURL(final String title, final String artist, final Handler handler) {
		Log.i(TAG, "LrcURL "+getQueryLrcURL(title, artist));
		new Thread(new Runnable() {
			@Override
			public void run() {
				String queryLrcURLStr = getQueryLrcURL(title, artist);
				//Logs.writeLog("拼接获取歌词文件url的请求地址", queryLrcURLStr);
				//Logs.writeLog("搜索 " + artist+"-"+title+".lrc", "搜啊搜啊搜啊搜啊搜啊搜啊搜啊");
				try {
					Message msg = new Message();
					msg.what = QUERY_ONLINE;
					msg.obj = null;
					handler.sendMessage(msg);//发送“正在联网搜索”消息
					
					URL url = new URL(queryLrcURLStr);
					URLConnection urlConnection = url.openConnection();
					urlConnection.connect();
					BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

					StringBuffer sb = new StringBuffer();

					String temp;
					while ((temp = in.readLine()) != null) {
						sb.append(temp);
					}

					JSONObject jObject = new JSONObject(sb.toString());
					//查找到的歌词文件url数量
					int count = jObject.getInt("count");
					if(count > 0) {
						//Logs.writeLog("搜索到远程歌词URL", count + "个");
						//查找成功
						int index = new Random().nextInt(count);
						JSONArray jArray = jObject.getJSONArray("result");
						JSONObject obj = jArray.getJSONObject(index);
						String lrcUrl = obj.getString("lrc");
						//Log.i(TAG, artist+"-"+title + ".lrc 查找索引--------" + lrcUrl);
						msg = new Message();
						msg.what = QUERY_ONLINE_OK;
						msg.obj = lrcUrl;
						handler.sendMessage(msg);
					}else { //查找失败 先不返回消息  再尝试一次只用歌曲名称来搜索
						//Log.i(TAG, artist+"-"+title + ".lrc 查找失败0个");
						//Logs.writeLog("搜索到远程歌词URL", count + "个");
						queryLrcURLStr = getQueryLrcURLOnlyTitle(title);
						urlConnection = new URL(queryLrcURLStr).openConnection();
						in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
						sb = new StringBuffer();
						temp = "";
						while ((temp = in.readLine()) != null) {
							sb.append(temp);
						}
						jObject = new JSONObject(sb.toString());
						//查找到的歌词文件url数量
						count = jObject.getInt("count");
						if(count > 0) {
							//查找成功
							int index = new Random().nextInt(count);
							JSONArray jArray = jObject.getJSONArray("result");
							JSONObject obj = jArray.getJSONObject(index);
							String lrcUrl = obj.getString("lrc");
							//Log.i(TAG, artist+"-"+title + ".lrc 查找索引--------" + lrcUrl);
							msg = new Message();
							msg.what = QUERY_ONLINE_OK;
							msg.obj = lrcUrl;
							handler.sendMessage(msg);
						}else {
							msg = new Message();
							msg.what = QUERY_ONLINE_NULL;
							msg.obj = null;
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					//查找失败
					//Log.i(TAG, artist+"-"+title + ".lrc 查找失败3");
					//Logs.writeLog("搜索远程歌词URL产生异常", e.getMessage());
					Message msg = new Message();
					msg.what = QUERY_ONLINE_FAIL;
					msg.obj = null;
					handler.sendMessage(msg);
				}
			}
		}).start();
	}


	/**
	 * 中文转码成UTF-8
	 * @param str
	 * @return
	 */
	public static String Encode(String str) {

		try {
			return URLEncoder.encode(str.trim(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return str;

	}


	/**
	 * 从网络加载并保存到本地
	 * @param urlPath 通过getLrcURL方法获得的远程歌词文件url
	 * @param lrcPath 要保存到本地的绝对路径
	 * @param handler 跨线程消息传输工具
	 * @return
	 */
	public void wrtieLrcContentFromUrlToLocal(final String urlPath, final String lrcPath, final Handler handler) {
		//Log.i(TAG, "lrcURL " + urlPath);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Message msg = new Message();
					msg.what = DOWNLOAD_ONLINE;
					msg.obj = "正在下载";
					handler.sendMessage(msg);
					
					URL url = new URL(urlPath);
					URLConnection urlConnection = url.openConnection();
					urlConnection.connect();
					HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
					if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
						File file = new File(lrcRootPath);
						if (!file.exists()) {
							file.mkdirs();
						}

						BufferedReader bf = new BufferedReader(new InputStreamReader(
								urlConnection.getInputStream(), "utf-8"));
						PrintWriter out = new PrintWriter(new BufferedWriter(
								new OutputStreamWriter(new FileOutputStream(lrcPath),"utf-8")));

						char c[] = new char[256];
						int temp = -1;
						while ((temp = bf.read()) != -1) {
							bf.read(c);
							out.write(c);
						}
						bf.close();
						out.close();
						Log.i(TAG, "正在下载 " + lrcPath);
						//下载成功
						msg= new Message();
						msg.what = DOWNLOAD_ONLINE_OK;
						msg.obj = "下载成功";
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
					//下载失败
					//Log.i(TAG, "lrcPath " + "下载失败2");
					Message msg = new Message();
					msg.what = DOWNLOAD_ONLINE_FAIL;
					msg.obj = "下载失败";
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	private String getLrcPath(String title, String artist) {
		return lrcRootPath + title + " - " + artist + ".lrc";
	}
}
